package com.ct.util;

import java.util.ArrayList;

public class HmacUtils {


    /**
     * 不添加接口传入参数
     *
     * @param appid
     * @param password
     * @param time
     * @return
     */
    public static String getAuthorization(String appid, String password, long time) {
        StringBuffer salt = new StringBuffer();
        String calDigest = "";
        ArrayList<String> nessArray = new ArrayList<String>();
        salt.append(appid).append(":");
        salt.append(time).append(":");

        StringBuffer buffer = new StringBuffer();
        buffer = getKeyValue(appid, time);
        // 加body
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("HmacSHA ");
        stringBuffer.append(salt);

        stringBuffer.append(new HMac().encode(password, buffer.toString()));

        nessArray = getIntMess(stringBuffer.toString());
        if (nessArray != null && nessArray.size() == 3) {
            calDigest = nessArray.get(2);
        }
        return calDigest;
    }




    //----
    /**
     * 获取接口中传入的参数 并且按照名字顺序排序 转换成要算法验证的格式
     *
     * @param appId
     * @param timestamp
     * @return
     */
    public static StringBuffer getKeyValue(String appId, long timestamp) {
        StringBuffer sb = new StringBuffer();
        sb.append("appid=" + appId + "&");
        sb.append("timestamp=" + timestamp);
        return sb;
    }


    /**
     * 获取调用方的头数据，解析出来时间和加密算法
     *
     * @param originalMess
     * @return
     */
    public static ArrayList<String> getIntMess(String originalMess) {
        ArrayList<String> messArray = new ArrayList<String>();
        String[] splitMess = originalMess.split(":");
        for (String s : splitMess) {
            messArray.add(s);
        }
        return messArray;
    }
}
